package com.flyme.module.base.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.base.client.entity.SysPlanrecord;
import com.flyme.module.base.provider.mapper.SysPlanrecordMapper;
import com.flyme.module.base.provider.service.SysAccountService;
import com.flyme.module.base.provider.service.SysPlanrecordService;
import com.flyme.module.base.provider.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * @author: zyf
 * @date: 2018/10/24 16:33
 * @description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysPlanrecordServiceImpl extends BaseServiceImpl<SysPlanrecordMapper, SysPlanrecord> implements SysPlanrecordService {

    @Autowired
    private SysUserService userService;

    /**
     * 循环插入记录
     */
    public boolean addPlanRecord(String userIds, Long planId, String deptIds){
        List<SysPlanrecord> list = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(userIds)){
            String[] userIdList = userIds.split(",");
            for(String userId : userIdList){
                Integer num = count(q().eq(true, "userId", userId).eq(true, "targetId", planId));
                if(num < 1){
                    SysPlanrecord plan = new SysPlanrecord();
                    plan.setUserId(userId);
                    plan.setIsRead(0);
                    plan.setTargetId(planId.toString());
                    list.add(plan);
                }
            }
        }
        if(ObjectUtils.isNotEmpty(deptIds)){
            String[] deptIdList = deptIds.split(",");
            List<String> userIdList = userService.selectByDept(deptIdList);
            for(String userId : userIdList){
                Integer num = count(q().eq(true, "userId", userId).eq(true, "targetId", planId));
                if(num < 1){
                    SysPlanrecord plan = new SysPlanrecord();
                    plan.setUserId(userId);
                    plan.setIsRead(0);
                    plan.setTargetId(planId.toString());
                    list.add(plan);
                }
            }
        }
        return saveBatch(list);
    }

    /**
     * 根据用户id改变计划记录状态
     */
    public boolean editStatus(Long userId){
        UpdateWrapper p = new UpdateWrapper();
        return update(p.set(true, "isRead", 1).eq(true, "userId", userId).eq(true, "isRead", 0));
    }

    /**
     * 根据用户统计未查看的计划
     */
    public Integer countByUser(Long userId){
        return count(q().eq(true, "userId", userId).eq(true, "isRead", 0));
    }
}
